<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>代下单</title>
    <link rel="stylesheet" href="plugins/layui/css/layui.css" media="all" />
    <link rel="stylesheet" href="css/comments.css" media="all">
    <link rel="stylesheet" href="css/treeTable.css">
    <style>
        #tableForm{
            padding: 10px 20px;
            display: none;

        }
        .my_address{
            display: none;
        }
		#tableForm{
			display: none;
            padding: 10px 20px;
		}
		#tableForm .layui-form-label{
            width: 90px;
        }

        /* 商品 */
        .goodsTable_box{
            position: relative;
            overflow: auto;
            margin-right: -1px;
            margin-bottom: -1px;
        }
        .tableAdd{
            cursor: pointer;
            margin-right: 10px;
        }
        .tableDel{
            cursor: pointer;
        }
        .goods_table_action_btn{
            font-weight: bold;
        }
        .goods_table_product_name_td,
        .goods_table_count_td{
            padding: 0!important;
        }
        .goods_table_main_img_td{
            padding: 0 15px!important;
        }
        .goods_table_product_name_td input,
        .goods_table_count_td input{
            border: 1px solid #f58843;
            /* box-shadow: 1px 1px 20px rgba(0, 0, 0, .15); */
            background: #ffffff;
            min-height: 36px;
            line-height: 36px;
            width: calc(100% - 22px);
            padding: 0 10px;
        }
        .goods_table_select_goods_list_box{
            position: absolute;
            border: 1px solid #d2d2d2;
            background-color: #fff;
            box-shadow: 0 2px 4px rgba(0,0,0,.12);
            margin: 5px 0;
            border-radius: 2px;
            z-index: 66666666;
            width: 399px;
            display: none;
        }
        .goods_table_select_goods_list{
            overflow: auto;
            max-height: 250px;
        }
        .goods_table_select_goods_list_empty{
            text-align: center;
            color: #999999;
            padding: 0 10px;
            line-height: 36px;
            font-weight: 400;
        }
        .goods_table_select_goods_list_item{
            padding: 0 10px;
            line-height: 36px;
            font-weight: 400;
            white-space: nowrap;
            cursor: pointer;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        .goods_table_select_goods_list_item:hover{
            background-color: #f2f2f2;
            -webkit-transition: .5s all;
            transition: .5s all;
        }
        .goods_table_select_goods_list_item.disabled{
            cursor: not-allowed;
            color: #cccccc;
        }
        .goods_table_select_goods_list_item.active{
            background-color: #f2f2f2;
        }
        .goods_table_product_name_cell{
            padding: 5px 16px;
        }
        .goods_table_cell{
            min-width: 100px;
        }
    </style>
</head>
<body>
    <div class="maincontainer" id="orderPlace">
        <blockquote class="layui-elem-quote">
            代下单
            <button type="button" class="layui-btn layui-btn-sm" style="float: right;margin-top: -4px;" onclick="window.history.back();">返回</button>
        </blockquote>
        
        <form class="layui-form" action="" lay-filter="example">
            <div class="layui-form-item">
                <label class="layui-form-label">食堂名称：</label>
                <div class="layui-input-inline">
                  <input type="text" name="canteenNameall" autocomplete="off" placeholder="请选择食堂" class="layui-input" id="demo">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">商品：</label>
                <div class="layui-input-inline">
                    <button type="button" class="layui-btn selectProduct">选择商品</button>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label"></label>
                <div class="layui-input-block goodsTable">
                    <div class="goodsTable_box">
                        <table class="layui-table" id="goodsTable" lay-filter="goodsTable">
                            <thead>
                                <tr>
                                    <td></td>
                                    <td></td>
                                    <td>商品名称</td>
                                    <td>商品图片</td>
                                    <td>规格</td>
                                    <td>单位</td>
                                    <td>数量（可编辑）</td>
                                    <td>单价（可编辑）</td>
                                    <td>小计</td>
                                </tr>
                            </thead>
                            <tbody>
                                <tr v-for="(item, index) in tableData">
                                    <td style="width: 18px;"><div style="width: 18px;">{{index + 1}}</div></td>
                                    <td class="goods_table_action_btn" style="width: 50px;">
                                        <div style="width: 50px;">
                                            <i class="layui-icon layui-icon-addition tableAdd" @click="ontableAdd"></i>
                                            <i class="layui-icon layui-icon-subtraction tableDel" v-show="tableData.length>1" @click="ontableDel(index)"></i>
                                        </div>
                                    </td>
                                    <td class="goods_table_product_name_td" v-if="!item.price" style="width: 400px;">
                                        <div class="goods_table_cell" style="width: 400px;">
                                            <input type="text" name="productName" placeholder="输入商品名称" autocomplete="off" v-model="item.productName" @input="onTableInput(index)" @focus="onTabelFocus(index)" @blur="onTableBlur()">
                                        </div>
                                    </td>
                                    <td v-else><div class="goods_table_cell" style="width: 400px;">{{item.productName}}</div></td>
                                    <td class="goods_table_main_img_td">
                                        <div class="goods_table_cell">
                                            <img v-if="item.mainImage" :src="TUrl+item.mainImage" alt="" width="50px" height="30px">
                                        </div>
                                    </td>
                                    <td><div class="goods_table_cell">{{item.skuName}}</div></td>
                                    <td><div class="goods_table_cell">{{item.unitName}}</div></td>
                                    <td class="goods_table_count_td" style="width: 200px;">
                                        <div class="goods_table_cell" style="width: 200px;">
                                            <input type='Number' oninput="if(value.length>6)value=value.slice(0,6)" v-model='item.count' @blur="onBlurFun(index)">
                                        </div>
                                    </td>
                                    <td class="goods_table_count_td" style="width: 200px;">
                                        <div class="goods_table_cell" style="width: 200px;">
                                            <input type='Number' oninput="if(value.length>6)value=value.slice(0,6)" v-model='item.price' @blur="onBlurPrice(index)">
                                        </div>
                                    </td>
                                    <td><div class="goods_table_cell">{{item.total}}</div></td>
                                </tr>
                                <tr>
                                    <td></td>
                                    <td></td>
                                    <td></td>
                                    <td></td>
                                    <td></td>
                                    <td></td>
                                    <td><div class="table_count_total">总数：<span style="color: #fbaf7e">0</span></div></td>
                                    <td></td>
                                    <td><div class="table_total">合计：<span style="color: #fbaf7e">￥0.00</span></div></td>
                                </tr>
                            </tbody>
                        </table>

                    </div>
                    <div class="goods_table_select_goods_list_box layui-anim layui-anim-fadein">
                        <div class="goods_table_select_goods_list" v-if="chooseGoodsList.length>0">
                            <div :class="'goods_table_select_goods_list_item '+(goodsIdSet.indexOf(citem.goodId)==-1?'':'disabled')"
                                v-for="(citem, cindex) in chooseGoodsList"
                                @click="onClickTableRender(cindex)"
                                @mouseout="onListBlur(cindex)"
                            >{{citem.productName}}</div>
                        </div>
                        <div v-else class="goods_table_select_goods_list_empty">没有找到相关数据</div>
                    </div>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">交货日期：</label>
                <div class="layui-inline">
                    <input type="text" class="layui-input" id="deliveryDate" placeholder="日期" autocomplete="off">
                </div>
                <div class="layui-inline">
                    <input type="text" class="layui-input" id="deliveryTime" placeholder="时间" autocomplete="off">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">卖家备注：</label>
                <div class="layui-input-block">
                    <textarea name="shopRemarks" placeholder="请输入卖家备注" class="layui-textarea" maxlength="140"></textarea>
                </div>
            </div>
            <div class="layui-form-item my_address">
                <label class="layui-form-label"></label>
                <div class="layui-input-block address">
                    <div style="margin-bottom: 8px;">
                        <i class="layui-icon layui-icon-location"></i>
                        <span class="receiveUser"></span>
                        <span class="receiveTelephone"></span>
                    </div>
                    <div style="margin-left: 20px;">
                        <span>地址：</span>
                        <span class="receiveAddressInfo"></span>
                    </div>
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button type="button" class="layui-btn" lay-submit="" lay-filter="demo1">确认</button>
                    <button type="button" class="layui-btn layui-btn-primary" onclick="window.history.back()">取消</button>
                </div>
            </div>
        </form>
    </div>
    <div id="tableForm">
        <form id="tablequeryForm" class="layui-form" action=""></form>
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label">商品名称：</label>
                    <div class="layui-input-inline">
                        <input type="text" name="productName" autocomplete="off" placeholder="商品名称" class="layui-input" maxlength="20">
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label">商品类别</label>
                    <div class="layui-input-inline">
                        <input type="text" name="categoryId" autocomplete="off" id="tree" lay-filter="tree" class="layui-input">
                    </div>
                </div>
                <div class="layui-inline">
                    <button type="button" class="layui-btn searchGoods">查询</button>
                    <button type="reset" class="layui-btn layui-btn-primary reReset" onclick="javascript:onReset()">重置</button>
                </div>
            </div>
        </form>
        <table class="layui-hide" id="selectTable" lay-filter="selectTable"></table>
    </div>
</body>
<script type="text/javascript" src="plugins/layui/layui.js"></script>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script src="js/vue.min.js"></script>
<script>
    new Vue({
        el: '#orderPlace',
        data: {
            TUrl: '',
            http: '',
            tableData: [{
                productName: '', // 商品名称
                mainImage: '', // 商品图片
                skuName: '', // 规格
                price: '', // 单价
                unitName: '', // 单位
                count: 1, // 数量（可编辑）
                total: 0, // 小计

            }],
            chooseGoodsList: [], // 可选择的商品列表
            _lastTime: '', // 商品表格下的input[name=productName]输入的最后时间
            goodsIdSet: [], // 选中的商品id集合
            goodsIdSetList: [''], // 选中的商品详情集合
            focusNum: null, // input[name=productName]选中第几行
            active: null, // 自动选中的商品列表

            canteenId: '', // 食堂id
        },
        mounted() {
            var _this = this
            layui.config({
                base: 'plugins/layui/modules/',
            }).use(['http', 'form', 'laydate', 'table', 'tableSelect', 'treeSelect'], function() {
                var http = layui.http,
                    form = layui.form,
                    laydate = layui.laydate,
                    table = layui.table,
                    tableSelect = layui.tableSelect,
                    treeSelect = layui.treeSelect;
                _this.TUrl = TUrl
                _this.http = http
                
                // 交货日期
                laydate.render({
                    elem: '#deliveryDate'
                    ,type: 'date'
                    ,theme: '#fbaf7e'
                });
                laydate.render({
                    elem: '#deliveryTime'
                    ,type: 'time'
                    ,theme: '#fbaf7e'
                    ,min: '08:00:00'
                    ,value: '08:00:00'
                });
                
                var authentication = localStorage.getItem('xi-can-supplier-authentication')

                // 供应商查询可以代下单的食堂列表
                tableSelect.render({
                    elem: '#demo',	//定义输入框input对象
                    checkedKey: 'id', //表格的唯一建值，非常重要，影响到选中状态 必填
                    searchKey: 'canteenName',	//搜索输入框的name值 默认keyword
                    searchPlaceholder: '食堂名称',	//搜索输入框的提示文字 默认关键词搜索
                    table: {	//定义表格参数，与LAYUI的TABLE模块一致，只是无需再定义表格elem
                        url: TUrl + 'supplier/admin/canteen/supplierListReplaceOrderCanteen',
                        headers: {
                            authentication: authentication
                        },
                        cols: [[
                            { type: 'radio' },
                            {field:'canteenName', title: '食堂名称', align : 'center'},
                            {field:'canteenContactUserName', title: '食堂联系人', align : 'center'}
                        ]],
                        response: {
                            statusCode : 200 //重新规定成功的状态码为 200，table 组件默认为 0
                        },
                        parseData: function(res) {
                            if (res.code == 402) {
                                location.href = "login.html";
                            }else if(res.code == 200){
                                return {
                                    "code": res.code, //状态字段名称
                                    "msg": res.msg, //消息字段
                                    "count": res.data.count, //总数字段
                                    "data":res.data.list  //数据字段
                                };

                            }else{
                                layer.msg(res.msg)
                            }
                        },
                        request: {
                            pageName : 'page', //页码的参数名称，默认：page,
                            limitName : 'limit' //每页数据量的参数名，默认：limit
                        }
                    },
                    radioChecked: function(checkedData) {
                        // // console.log(checkedData)
                        $('input[name=canteenNameall]').val(checkedData[0].canteenName)
                        _this.canteenId = checkedData[0].id
                        // 地址
                        $('.my_address').show()
                        $('.receiveUser').html( checkedData[0].canteenContactUserName)
                        $('.receiveTelephone').html( checkedData[0].canteenContactUserTelephone)
                        $('.receiveAddressInfo').html( checkedData[0].receiveAddress)
                        tableSelect.hide();
                    }
                })
                // 分类查询
                getCategory()
                function getCategory() {
                    treeSelect.render({
                        // 选择器
                        elem: '#tree',
                        // 数据
                        data: TUrl + 'supplier/admin/product/category/listAll',
                        // 异步加载方式：get/post，默认get
                        type: 'get',
                        headers: {
                            authentication: authentication
                        },
                        // 占位符
                        placeholder: '商品类别',
                        // 是否开启搜索功能：true/false，默认false
                        search: true,
                        style: {
                            folder: {
                                enable: false
                            },
                            line: {
                                enable: true
                            }
                        },
                        // 点击回调
                        click: function(d){
                            // console.log(d);
                            selectTable.reload({
                                page:{curr:1},
                                where: {
                                    productName: $('#tableForm input[name=productName]').val(),
                                    categoryId: $('#tableForm input[name=categoryId]').val()
                                }
                            })
                        },
                        // 加载完成后的回调函数
                        success: function (d) {
                            // // console.log(d);
                            
                        }
                    });
                }
                
                // 选择商品
                $(document).on('click','.selectProduct',function(){
                    tableFun()
                    http.myOpen({
                        title:'选择商品',
                        content: $('#tableForm'),
                        area:['850px','500px'],
                        btn:['确定','取消'],
                        btn1:function(index, layero){
                            if (moregoodsIdSetList.length == 0) {
                                layer.msg("请勾选需要的商品");
                                return;
                            }
                            _this.myRenderGoodsTable(moregoodsIdSetList)
                            layer.close(index)
                        }
                    })
                })
                // 重置
                window.onReset = function() {
                    $('#tableForm input[name=productName]').val('')
                    treeSelect.revokeNode('tree', function(d){});
                }
                // 可选择的商品列表
                var table_data
                function tableFun(){
                    selectTable = http.table({
                        elem: '#selectTable',
                        url: 'supplier/admin/product/supplierListGoods',
                        method: 'get',
                        id: 'selectTable',
                        height: 315,
                        done: function(res, curr, count){
                            var data = res.data;
                            table_data = data
                            //在缓存中找到id ,然后设置data表格中的选中状态
                            //循环所有数据，找出对应关系，设置checkbox选中状态
                            for(var i=0;i< res.data.length;i++){
                                //数据id和要勾选的id相同时checkbox选中
                                if(moregoodsIdSet.indexOf(res.data[i].goodId)!=-1){ // 选中了
                                    //这里才是真正的有效勾选
                                    res.data[i]["LAY_CHECKED"]='true';
                                    //找到对应数据改变勾选样式，呈现出选中效果
                                    var index= res.data[i]['LAY_TABLE_INDEX'];
                                    $('#tableForm .layui-table-fixed-l tr[data-index=' + index + '] input[type="checkbox"]').prop('checked', true);
                                    $('#tableForm .layui-table-fixed-l tr[data-index=' + index + '] input[type="checkbox"]').next().addClass('layui-form-checked');
                                }
                                if(_this.goodsIdSet.indexOf(res.data[i].goodId)!=-1){ // 已经选过
                                    $("#tableForm .layui-table tr[data-index="+i+"] input[type='checkbox']").prop('disabled',true);
                                    $("#tableForm .layui-table tr[data-index="+i+"] input[type='checkbox']").next().addClass('layui-btn-disabled')
                                }
                            }
                            //设置全选checkbox的选中状态，只有改变LAY_CHECKED的值， table.checkStatus才能抓取到选中的状态
                            var checkStatus = table.checkStatus('selectTable');
                            if(checkStatus.isAll){
                                $('#tableForm .layui-table-header th[data-field="0"] input[type="checkbox"]').prop('checked', true);
                                $('#tableForm .layui-table-header th[data-field="0"] input[type="checkbox"]').next().addClass('layui-form-checked');
                            }
                            $(".layui-table-header th[data-field='0'] .layui-form-checkbox").hide()
                        },
                        cols: [[
                            {type:'checkbox',fixed: true},
                            {field:'productName', title: '商品名称', align : 'center'},
                            {field:'productCategoryName', title: '商品类别', align : 'center'},
                            {field:'skuName', title: '规格', align : 'center'},
                            {field:'price', title: '单价', align : 'center'},
                            {field:'unitName', title: '单位', align : 'center'}
                        ]]
                    })
                }
                //复选框选中监听,将选中的id 设置到缓存数组,或者删除缓存数组
                var moregoodsIdSetList = [], moregoodsIdSet = []

                table.on('checkbox(selectTable)', function (obj) {
                    var checkStatus = table.checkStatus('selectTable'); //获取选中行状态
                    var data = checkStatus.data; //获取选中行数据
                    for(var n=0;n<moregoodsIdSetList.length;n++){
                        for(var m=0;m<table_data.length;m++){
                            if(moregoodsIdSetList[n].goodId == table_data[m].goodId){
                                moregoodsIdSetList.splice(n,1)
                                n--
                                break
                            }
                        }
                    }
                    var list
                    if(moregoodsIdSetList.length == 0){
                        list = data
                    }else{
                        list = moregoodsIdSetList.concat(data)
                    }
                    moregoodsIdSetList = unique5(list)
                    function unique5(arr){
                        moregoodsIdSet=[];
                        var hashList=[]
                        for (var i = 0; i < arr.length; i++) {
                            if(moregoodsIdSet.indexOf(arr[i].goodId)==-1){
                                moregoodsIdSet.push(arr[i].goodId);
                                hashList.push(arr[i])
                            }
                        }
                        return hashList;
                    }
                });
                
                // 查询
                let _lastTime = null
                $(document).on("input","#tableForm input[name=productName]", function () {
                    let _nowTime = + new Date()
                    if (_nowTime - _lastTime > 500 || !_lastTime) {
                        selectTable.reload({
                            page:{curr:1},
                            where: {
                                productName: $('#tableForm input[name=productName]').val(),
                                categoryId: $('#tableForm input[name=categoryId]').val()
                            }
                        })
                        _lastTime = _nowTime
                    }
                })
                $(document).on('click','.searchGoods',function(){
                    selectTable.reload({
                        page:{curr:1},
                        where: {
                            productName: $('#tableForm input[name=productName]').val(),
                            categoryId: $('#tableForm input[name=categoryId]').val()
                        }
                    })
                })

                //监听提交
                form.on('submit(demo1)', function(data){
                    // console.log(data.field)
                    if(!_this.canteenId){
                        layer.msg('请选择食堂')
                        return
                    }
                    if(_this.goodsIdSetList.length == 0){
                        layer.msg('请选择商品')
                        return
                    }
                    var flag = false
                    var el = $('.table_edit_div')
                    for(var j=0;j<el.length;j++){
                        if($.trim(el.eq(j).html()) == ''){
                            flag = true
                            break
                        }
                    }
                    if(flag){
                        layer.msg('请填写商品数量')
                        return
                    }
                    var singleOrderList = []
                    for(var i=0;i<_this.goodsIdSetList.length;i++){
                        if(_this.goodsIdSetList[i]){
                            singleOrderList.push({
                                goodId: _this.goodsIdSetList[i].goodId, // 商品id
                                count: Number(_this.goodsIdSetList[i].count), // 数量
                                goodPrice: Number(_this.goodsIdSetList[i].modifyprice) // 单价
                            })
                        }
                    }
                    if(singleOrderList.length == 0){
                        layer.msg('请选择商品')
                        return
                    }
                    if(!$('#deliveryDate').val()||!$('#deliveryTime').val()){
                        layer.msg('请选择交货日期')
                        return
                    }
                    http.postJSON('supplier/admin/shop/order/replaceOrder',JSON.stringify({
                        canteenId: _this.canteenId,
                        singleOrderList: singleOrderList,
                        deliveryTime: $('#deliveryDate').val()+' '+$('#deliveryTime').val(),
                        supplierRemarks: $('textarea[name=shopRemarks]').val() // 卖家备注
                    }), function(res) {
                        if(res.code == 200){
                            layer.msg('操作成功')
                            setTimeout(function(){
                                window.history.back()
                            },500)
                        }else{
                            layer.msg(res.msg)
                        }
                    })
                })
            })
        },
        methods: {
            // 模糊查询商品列表
            getGoodsListMore(productName){
                console.log(productName)
                if (!this.canteenId){
                    layer.msg('请选择食堂')
                    return
                }
                var _this = this
                this.http.get('supplier/admin/product/supplierListGoods',{
                    canteenId: this.canteenId,
                    productName: productName,
                    page: 1,
                    limit: 20
                }, function(res){
                    if(res.code == 200){
                        _this.chooseGoodsList = res.data.list
                        
                        for(var i=0;i<_this.chooseGoodsList.length;i++){
                            if(_this.goodsIdSet.indexOf(_this.chooseGoodsList[i].goodId)==-1){ // 可选
                                $('.goods_table_select_goods_list_item').eq(i).addClass('active')
                                _this.active = i
                                break
                            }
                        }
                    }else{
                        layer.msg(res.msg)
                    }
                })
            },
            // 添加一条
            ontableAdd() {
                this.tableData.push({
                    productName: '', // 商品名称
                    mainImage: '', // 商品图片
                    skuName: '', // 规格
                    price: '', // 单价
                    unitName: '', // 单位
                    count: 1, // 数量（可编辑）
                    total: 0, // 小计
                })
                
                this.goodsIdSetList.push('')
            },
            // 删除一条
            ontableDel(index){
                this.tableData.splice(index, 1)
                if(this.goodsIdSetList.length > index){
                    if(this.goodsIdSetList[index]) {
                        var delGoodsId = this.goodsIdSetList[index].goodId
                        var delIndex = this.goodsIdSet.indexOf(delGoodsId)
                        if(delIndex != -1) {
                            this.goodsIdSet.splice(delIndex, 1)
                        }
                    }
                    this.goodsIdSetList.splice(index, 1)
                    
                }
                this.getTotal() // 计算合计
            },
            // 光标进入到input
            onTabelFocus(index) {
                var _this = this
                var $el = $('#goodsTable tbody tr').eq(index).find('input[name=productName]')
                this.getGoodsListMore($el.val()) // 查询商品列表
                setTimeout(function(){
                    $('.goods_table_select_goods_list_box').show()
                    var position = $el.parent().parent().position()
                    _this.focusNum = index
                    console.log(position)
                    $('.goods_table_select_goods_list_box').css("top", position.top+38)
                    $('.goods_table_select_goods_list_box').css("left", position.left)
                    
					$(document).on('keydown', _this.enterConfirm); //监听键盘事件
			
                },500)
            },
            // 光标离开input
            onTableBlur() {
                var _this = this
                $(document).off('keydown', _this.enterConfirm); //解除键盘事件
                setTimeout(function(){
                    $('.goods_table_select_goods_list_box').hide()
                },300)
            },
            enterConfirm(event){
                console.log(event.keyCode)
                if(event.keyCode === 13){ // enter
                    this.onClickTableRender(this.active)
                }else if(event.keyCode === 40){ // down
                    if(this.active < this.chooseGoodsList.length-1){
                        var active = this.downpSelectActive(this.active) // 键盘向下判断可选项
                        if(active == this.active){
                            return
                        }
                        $(".goods_table_select_goods_list").animate({scrollTop:active*36},100);
                        $('.goods_table_select_goods_list_item').eq(this.active).removeClass('active')
                        $('.goods_table_select_goods_list_item').eq(active).addClass('active')
                        this.active = active

                    }
                }else if(event.keyCode === 38){ // up
                    if(this.active !== 0){
                        var active = this.upSelectActive(this.active) // 键盘向上判断可选项
                        if(active == this.active){
                            return
                        }
                        $(".goods_table_select_goods_list").animate({scrollTop:active*36},100);
                        $('.goods_table_select_goods_list_item').eq(this.active).removeClass('active')
                        $('.goods_table_select_goods_list_item').eq(active).addClass('active')
                        this.active = active

                    }
                }
            },
            // 键盘向下判断可选项
            downpSelectActive(index) {
                for(var i=index+1;i<this.chooseGoodsList.length;i++){
                    if(this.goodsIdSet.indexOf(this.chooseGoodsList[i].goodId)==-1){ // 可选
                        return i
                    }
                }
                return index
            },
            // 键盘向上判断可选项
            upSelectActive(index) {
                for(var i=index-1;i>-1;i--){
                    if(this.goodsIdSet.indexOf(this.chooseGoodsList[i].goodId)==-1){ // 可选
                        return i
                    }
                }
                return index
            },
            onListBlur(index) {
                $('.goods_table_select_goods_list_item').eq(index).removeClass('active')
            },
            // 监听商品表格下的input[name=productName]输入
            onTableInput(index) {
                let _nowTime = + new Date()
                if (_nowTime - this._lastTime > 100 || !this._lastTime) {
                    // 模糊查询商品列表
                    var $el = $('#goodsTable tbody tr').eq(index).find('input[name=productName]')
                    this.getGoodsListMore($el.val())
                    this._lastTime = _nowTime
                }
            },
            // 选择商品，回显表格
            onClickTableRender(index) {
                var list = this.chooseGoodsList[index]
                if(this.goodsIdSet.indexOf(list.goodId)!==-1){ // 禁止选择
                    return
                }
                list.modifyprice = list.price
                list.count = 1
                this.$set(this.goodsIdSetList, this.goodsIdSetList.length-1, list); // 把选中的商品放入列表中
                this.goodsIdSet.push(list.goodId)

                // 更新这一行的数据
                this.$set(this.tableData, this.tableData.length-1,{
                    productName: list.productName, // 商品名称
                    mainImage: list.mainImage, // 商品图片
                    skuName: list.skuName, // 规格
                    unitName: list.unitName, // 单位
                    price: list.price, // 单价（可编辑）
                    count: 1, // 数量（可编辑）
                    total: list.price * 1, // 小计
                })
                this.ontableAdd() // 添加一条
                this.getTotal() // 计算合计
            },
            // 修改数量
            onBlurFun(index) {
                if(!this.goodsIdSetList[index]){
                    return
                }
                var item = this.tableData[index]

                var value = item.count
                if(!value){
                    value = 1
                }
                if(this.goodsIdSetList[index].unitDecimalStatus == 1){ // 允许输入小数
                    var reg = /^((0|[1-9]\d{0,})((\.[0-9]{1,2})?))$/;
                    if(!reg.test(value)) {
                        layer.msg('当前商品数量格式有误')
                        value = this.goodsIdSetList[index].count
                    }

                }else{ // 不允许输入小数
                    var regex = /^(0|[1-9][0-9]*)$/;
                    if(!regex.test(value)) {
                        layer.msg('当前商品数量只能为整数')
                        value = this.goodsIdSetList[index].count
                    }
                }

                this.goodsIdSetList[index].count = value
                item.count = value
                item.total = Math.round(item.price * value * 100 ) / 100
                this.$set(this.tableData, index, item)
                this.getTotal() // 计算合计
            },
            // 计算合计
            getTotal() {
                var orderTotalMoney = 0
                var orderTotalCount = 0
                for(var i=0;i<this.goodsIdSetList.length;i++){
                    if(this.goodsIdSetList[i]){
                        orderTotalCount += Number(this.goodsIdSetList[i].count)
                        if(this.goodsIdSetList[i].count){
                            orderTotalMoney += Number(this.goodsIdSetList[i].modifyprice) * Number(this.goodsIdSetList[i].count)
                        }
                    }
                }
                $('.table_count_total').html('总数：<span style="color: #fbaf7e">'+orderTotalCount+'</span></div>')
                $('.table_total').html('合计：<span style="color: #fbaf7e">￥'+orderTotalMoney.toFixed(2)+'</span>')
            },
            // 修改单价
            onBlurPrice(index) {
                if(!this.goodsIdSetList[index]){
                    return
                }
                var item = this.tableData[index]

                var value = item.price
                if(!value){
                    value = this.goodsIdSetList[index].price
                }
                
                this.goodsIdSetList[index].modifyprice = value
                item.price = value
                item.total = Math.round(item.count * value * 100 ) / 100
                this.$set(this.tableData, index, item)
                this.getTotal() // 计算合计
            },
            // 更新选中商品表格数据
            myRenderGoodsTable(list){
                console.log(list)
                for(var i=0;i<list.length;i++){
                    list[i].count = 1
                    list[i].modifyprice = list[i].price
                    this.$set(this.goodsIdSetList, this.goodsIdSetList.length-1, list[i]) // 把选中的商品放入列表中
                    this.goodsIdSet.push(list[i].goodId)
                    // 更新这一行的数据
                    this.$set(this.tableData, this.tableData.length-1,{
                        productName: list[i].productName, // 商品名称
                        mainImage: list[i].mainImage, // 商品图片
                        skuName: list[i].skuName, // 规格
                        price: list[i].price, // 单价
                        unitName: list[i].unitName, // 单位
                        count: 1, // 数量（可编辑）
                        total: list[i].price * 1, // 小计
                    })
                    this.ontableAdd() // 添加一条
                }
                this.getTotal() // 计算合计
            }
        }
    })

</script>
</html>